//
//  VPLoginViewController.m
//  VPLoginComponentForPod
//
//  Created by verne on 2016/12/28.
//  Copyright © 2016年 vernepung. All rights reserved.
//
#import "UtilsMacro.h"
#import "VPLoginViewController.h"
#import "VPLoginLeftCell.h"
#import "VPLoginRightCell.h"
#import "UIView+Additional.h"
#import "Helper+Validate.h"
#import "UIView+Toast.h"
#import "ConstMacro.h"
@interface VPLoginViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIGestureRecognizerDelegate,UITextFieldDelegate>{
    UIImage *showPasswordImage;
    UIImage *hidePasswordImage;
}
@property (weak, nonatomic) IBOutlet UIImageView *imgLogoImageView;
@property (weak, nonatomic) IBOutlet UIButton *btnLogin;
@property (weak, nonatomic) IBOutlet UICollectionView *commandCollectionView;
@property (weak, nonatomic) IBOutlet UITextField *txtUserName;
@property (weak, nonatomic) IBOutlet UIButton *btnPasswordState;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *btnPasswordStateWidthConstraint;
@property (weak, nonatomic) IBOutlet UITextField *txtPassword;
@property (weak, nonatomic) IBOutlet UILabel *txtCopyright;

@property (strong, nonatomic) UITextField *currentEditingTextField;
@end

@implementation VPLoginViewController
#pragma mark - life cycle
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)setupViews{
    self.view.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapSelf)];
    tapGesture.cancelsTouchesInView = YES;
    tapGesture.delegate = self;
    [self.view addGestureRecognizer:tapGesture];
    [self.commandCollectionView registerNib:[UINib nibWithNibName:@"VPLoginLeftCell" bundle:nil]  forCellWithReuseIdentifier:@"VPLoginLeftCell"];
    [self.commandCollectionView registerNib:[UINib nibWithNibName:@"VPLoginRightCell" bundle:nil]  forCellWithReuseIdentifier:@"VPLoginRightCell"];
    self.commandCollectionView.backgroundColor = self.view.backgroundColor;
    [self configViews];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self regisiterNotification];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - UITextFieldDelegate

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    _currentEditingTextField = textField;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == self.txtUserName){
        [self.txtPassword becomeFirstResponder];
    }else if (textField == self.txtPassword){
        [self.view endEditing:YES];
        [self btnLoginClicked:self.btnLogin];
    }
    return YES;
}

#pragma mark - UIGestureRecognizerDelegate
-(BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch {
    if([[touch.view.superview class] isSubclassOfClass:[UICollectionViewCell class]]){
        return NO;
    }
    return YES;
}

#pragma mark - UICollectionViewDataSource
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ExecBlock(self.executedCommandBlock,indexPath.row);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    if (row % 2 == 0){
        VPLoginLeftCell *leftCell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([VPLoginLeftCell class]) forIndexPath:indexPath];
        leftCell.backgroundColor = leftCell.contentView.backgroundColor = self.view.backgroundColor;
        [leftCell fillCellWithTitle:self.commandTitles[row] imageName:self.commandImages[row]];
        return leftCell;
    }else{
        VPLoginRightCell *rightCell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([VPLoginRightCell class]) forIndexPath:indexPath];
        rightCell.backgroundColor = rightCell.contentView.backgroundColor = self.view.backgroundColor;
        [rightCell fillCellWithTitle:self.commandTitles[row] imageName:self.commandImages[row]];
        return rightCell;
    }
    return [UICollectionViewCell new];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.commandTitles.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat w = (self.commandCollectionView.frame.size.width - 10) / 2;
    return CGSizeMake(w,35.f);
}

#pragma mark - keyboard
- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] doubleValue]];
    [UIView setAnimationDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    self.view.transform = CGAffineTransformIdentity;
    [UIView commitAnimations];
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    NSValue* frameValue = notification.userInfo[UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame;
    [frameValue getValue:&keyboardFrame];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] doubleValue]];
    [UIView setAnimationDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
//    self.view.transform = CGAffineTransformMakeTranslation(0, keyboardFrame.size.height);
//    _contentScrollView.contentInset = UIEdgeInsetsMake(0, 0, keyboardFrame.size.height, 0);
//    _contentScrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, keyboardFrame.size.height, 0);
    [UIView commitAnimations];
    
    CGRect nowFrame = self.view.frame;
    
    nowFrame.size.height -= keyboardFrame.size.height;
    CGPoint bottomPoint = CGPointMake(self.currentEditingTextField.origin.x, self.currentEditingTextField.origin.y + self.currentEditingTextField.height + 10);
    if (!CGRectContainsPoint(nowFrame, bottomPoint))
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationCurve:[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] doubleValue]];
        [UIView setAnimationDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] > 0 ?: 0.25];
//        [_contentScrollView scrollRectToVisible:self.currentEditingTextField.frame animated:NO];
        
        self.view.transform = CGAffineTransformMakeTranslation(0, keyboardFrame.size.height - self.currentEditingTextField.bottom - self.currentEditingTextField.height - 10);
        [UIView commitAnimations];
    }
}


#pragma mark - private
- (IBAction)btnPasswordStateClicked:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.txtPassword.secureTextEntry = !sender.selected;
}

- (void)configViews{
    self.txtUserName.text = self.oldUserName;
    self.txtPassword.text = self.oldPassword;
    if (self.userNameLeftIcon){
        UIImage *userNameLeftImage = [UIImage imageNamed:self.userNameLeftIcon];
        if (userNameLeftImage){
            UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, userNameLeftImage.size.width + 10, self.txtUserName.height)];
            UIImageView *leftIcon = [[UIImageView alloc]initWithImage:userNameLeftImage];
            leftIcon.frame = CGRectMake(5, (self.txtUserName.height - userNameLeftImage.size.height) / 2, userNameLeftImage.size.width, userNameLeftImage.size.height);
            [leftView addSubview:leftIcon];
            self.txtUserName.leftView = leftView;
            self.txtUserName.leftViewMode = UITextFieldViewModeAlways;
        }
    }
    
    if (self.passwordLeftIcon){
        UIImage *passwordLeftImage = [UIImage imageNamed:self.passwordLeftIcon];
        if (passwordLeftImage){
            UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, passwordLeftImage.size.width + 10, self.txtPassword.height)];
            UIImageView *leftIcon = [[UIImageView alloc]initWithImage:passwordLeftImage];
            leftIcon.frame = CGRectMake(5, (self.txtPassword.height - passwordLeftImage.size.height) / 2, passwordLeftImage.size.width, passwordLeftImage.size.height);
            [leftView addSubview:leftIcon];
            self.txtPassword.leftView = leftView;
            self.txtPassword.leftViewMode = UITextFieldViewModeAlways;
        }
    }
    showPasswordImage = [UIImage imageNamed:self.showPasswordImageName];
    hidePasswordImage = [UIImage imageNamed:self.hidePasswordImageName];
    if (showPasswordImage && hidePasswordImage){
        [self.btnPasswordState setImage:showPasswordImage forState:UIControlStateNormal];
        [self.btnPasswordState setImage:hidePasswordImage forState:UIControlStateSelected];
    }else{
        self.btnPasswordStateWidthConstraint.constant = 0;
    }
    if (![Helper isBlankString:self.logoName]){
        [self.imgLogoImageView setImage:[UIImage imageNamed:self.logoName]];
    }
    [self.btnLogin setBackgroundColor:self.loginButtonBackgroundColor ?: [UIColor grayColor]];
    if (![Helper isBlankString:self.copyright]){
        self.txtCopyright.text = self.copyright;
        self.txtCopyright.textColor = self.copyrightLabelTextColor;
        self.txtCopyright.font = self.copyrightLabelFont;
        [self.view updateConstraintsIfNeeded];
    }
}

- (void)regisiterNotification{
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)tapSelf{
    [self.view endEditing:YES];
}

- (IBAction)btnLoginClicked:(id)sender {
    NSString *profileName = self.txtUserName.text;
    NSString *password = self.txtPassword.text;
    if ([Helper isBlankString:profileName]){
        [self.view makeToast:@"用户名不能为空"];
        [self.txtUserName becomeFirstResponder];
        return;
    }
    if ([Helper isBlankString:password]){
        [self.view makeToast:@"密码不能为空"];
        [self.txtPassword becomeFirstResponder];
        return;
    }
    [self.view endEditing:YES];
    [self showProgressViewWithTitle:kJustWaiting];
    if (self.btnLoginClickedBlock){
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSString *loginMessage = self.btnLoginClickedBlock(@{@"profileName":self.txtUserName.text,@"password":self.txtPassword.text});
            if (loginMessage){
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.view makeToast:loginMessage];
                    [self hideProgressView];
                });
            }
        });
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
